package org.dromara.web.CssUtil;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.app.cssUtils.CssExceptionDescription;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.app.domain.*;
import org.dromara.app.mapper.SkAppUserMapper;
import org.dromara.app.mapper.SkPriceLogMapper;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.redis.utils.CacheUtils;
import org.dromara.system.domain.SysConfig;
import org.dromara.system.mapper.SysConfigMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;

@RequiredArgsConstructor
@Service
public class CssOrderServer {

    private final SkAppUserMapper skAppUserMapper;

    private final SysConfigMapper sysConfigMapper;

    private final SkPriceLogMapper skPriceLogMapper;

    /**
     * 分销-开会员分配佣金 Member distribution commission
     */
    @Async
    public void memberDistributionCommission(SkMembershipOrder sk) {
        SkAppUser appUser = skAppUserMapper.selectById(sk.getUserId());
        BigDecimal balance = sk.getPrice();
        //判断是否有邀请人
        if (appUser != null && appUser.getYqUserId() != null) {
            SkAppUser sjUser = skAppUserMapper.selectById(appUser.getYqUserId());
            //判断是否是合伙人
            if (sjUser.getIsHehuo().longValue() == 1) {
                SysConfig sysConfig = getConfig(CacheNames.SYS_CONFIG, CssUtils.getFenXiaoConfig("合伙人开会员佣金"));
                BigDecimal hhPrice = sk.getPrice().multiply(new BigDecimal(sysConfig.getConfigValue())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                activeAccount(sjUser, hhPrice, 12L, "合伙人开会员佣金-订单：" + sk.getOrderSn() + "-用户：" + sk.getUserId());
                balance = balance.subtract(hhPrice);
            } else {
                //判断是否是推广达人
                if (sjUser.getIsTgDaren().longValue() == 1) {
                    SysConfig sysConfig = getConfig(CacheNames.SYS_CONFIG, CssUtils.getFenXiaoConfig("推广达人开会员佣金"));
                    BigDecimal tgdrPrice = sk.getPrice().multiply(new BigDecimal(sysConfig.getConfigValue())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                    balance = balance.subtract(tgdrPrice);
                    activeAccount(sjUser, tgdrPrice, 11L, "推广达人开会员佣金-订单：" + sk.getOrderSn() + "-用户：" + sk.getUserId());
                } else {
                    //判断是否是达人
                    if (sjUser.getUserType().longValue() == 2) {
                        SysConfig sysConfig = getConfig(CacheNames.SYS_CONFIG, CssUtils.getFenXiaoConfig("达人开会员佣金"));
                        BigDecimal drPrice = sk.getPrice().multiply(new BigDecimal(sysConfig.getConfigValue())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                        balance = balance.subtract(drPrice);
                        activeAccount(sjUser, drPrice, 10L, "达人开会员佣金-订单：" + sk.getOrderSn() + "-用户：" + sk.getUserId());
                    }
                }

            }
            //城市代理
            if (balance.compareTo(BigDecimal.ZERO) > 0) {
                if (sk.getCity() != null) {
                    SkAppUser cityUser = skAppUserMapper.selectOne(
                        new QueryWrapper<SkAppUser>().lambda()
                            .eq(SkAppUser::getDailiState, 1)
                            .eq(SkAppUser::getDailiCityTitle, sk.getCity())
                    );
                    if (cityUser != null) {
                        SysConfig sysConfig = getConfig(CacheNames.SYS_CONFIG, CssUtils.getFenXiaoConfig("城市代理开会员佣金"));
                        BigDecimal cityPrice = sk.getPrice().multiply(new BigDecimal(sysConfig.getConfigValue())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                        balance = balance.subtract(cityPrice);
                        if (balance.compareTo(cityPrice) <= 0) {
                            cityPrice = balance;
                        }
                        activeAccount(sjUser, cityPrice, 13L, "城市代理开会员佣金-订单：" + sk.getOrderSn() + "-用户：" + sk.getUserId());
                    }
                }
            }
        }
    }

    /**
     * 分销达人订单分配佣金
     *
     * @return
     */
    @Async
    public void memberDistributionCommissionOrder(SkYueDanOrder order) {
        SkAppUser appUser = skAppUserMapper.selectById(order.getUserId());
        BigDecimal balance = order.getPayPrice();

        //给达人佣金
        SysConfig sysConfig2 = getConfig(CacheNames.SYS_CONFIG, CssUtils.getFenXiaoConfig("达人订单佣金"));
        BigDecimal drPrice = order.getPayPrice().multiply(new BigDecimal(sysConfig2.getConfigValue())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
        balance = balance.subtract(drPrice);
        SkAppUser daren = skAppUserMapper.selectById(order.getDarenUserId());
        activeAccount(daren, drPrice, 14L, "达人订单佣金-订单：" + order.getOrderSn() + "-用户：" + order.getUserId());

        //判断是否有邀请人
        if (appUser != null && appUser.getYqUserId() != null) {
            SkAppUser sjUser = skAppUserMapper.selectById(appUser.getYqUserId());
            //判断是否是合伙人
            if (sjUser.getIsHehuo().longValue() == 1) {
                SysConfig sysConfig = getConfig(CacheNames.SYS_CONFIG, CssUtils.getFenXiaoConfig("合伙人订单佣金"));
                BigDecimal hhPrice = order.getPayPrice().multiply(new BigDecimal(sysConfig.getConfigValue())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                activeAccount(sjUser, hhPrice, 16L, "合伙人订单佣金-订单：" + order.getOrderSn() + "-用户：" + order.getUserId());
                balance = balance.subtract(hhPrice);
            } else {
                //判断是否是推广达人
                if (sjUser.getIsTgDaren().longValue() == 1) {
                    SysConfig sysConfig = getConfig(CacheNames.SYS_CONFIG, CssUtils.getFenXiaoConfig("推广达人订单佣金"));
                    BigDecimal tgdrPrice = order.getPayPrice().multiply(new BigDecimal(sysConfig.getConfigValue())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                    balance = balance.subtract(tgdrPrice);
                    activeAccount(sjUser, tgdrPrice, 15L, "推广达人订单佣金-订单：" + order.getOrderSn() + "-用户：" + order.getUserId());
                }

            }
            //城市代理
            if (balance.compareTo(BigDecimal.ZERO) > 0) {
                if (order.getCity() != null) {
                    SkAppUser cityUser = skAppUserMapper.selectOne(
                        new QueryWrapper<SkAppUser>().lambda()
                            .eq(SkAppUser::getDailiState, 1)
                            .eq(SkAppUser::getCity, order.getCity())
                    );
                    if (cityUser != null) {
                        SysConfig sysConfig = getConfig(CacheNames.SYS_CONFIG, CssUtils.getFenXiaoConfig("城市代理订单佣金"));
                        BigDecimal cityPrice = order.getPayPrice().multiply(new BigDecimal(sysConfig.getConfigValue())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                        balance = balance.subtract(cityPrice);
                        if (balance.compareTo(cityPrice) <= 0) {
                            cityPrice = balance;
                        }
                        activeAccount(sjUser, cityPrice, 17L, "城市代理订单佣金-订单：" + order.getOrderSn() + "-用户：" + order.getUserId());
                    }
                }
            }
        }
    }

    //查询参数
    public SysConfig getConfig(String cacheNames, Object key) {
        SysConfig sysConfig = CacheUtils.get(CacheNames.SYS_CONFIG, key);
        if (sysConfig == null) {
            sysConfig = sysConfigMapper.selectOne(
                new QueryWrapper<SysConfig>().lambda()
                    .eq(SysConfig::getConfigKey, key)
                    .last("limit 1")
            );
            CacheUtils.put(cacheNames, key, sysConfig);
        }
        return sysConfig;
    }

    //账户金额操作
    public void activeAccount(SkAppUser skAppUser, BigDecimal price, Long type, String content) {
        SkPriceLog sk = new SkPriceLog();
        sk.setPrice(price);
        sk.setUserId(skAppUser.getId());
        sk.setOldPrice(skAppUser.getPrice());
        sk.setType(type);
        sk.setTitle(content);
        skPriceLogMapper.insert(sk);
        skAppUserMapper.activePrice(skAppUser.getId(), price);
    }

    /**
     * 开通会员余额操作
     *
     * @param skAppUser
     * @param price
     * @param type
     * @param content
     */
    public void activevipAccount(SkAppUser skAppUser, SkVipPrice price, Long type, String content) {
        SkPriceLog sk = new SkPriceLog();
        sk.setPrice(price.getPrice().negate());
        sk.setUserId(skAppUser.getId());
        sk.setOldPrice(skAppUser.getPrice());
        sk.setType(type);
        sk.setTitle(content);
        skPriceLogMapper.insert(sk);
        skAppUserMapper.activeVipPrice(skAppUser.getId(), sk.getPrice(), DateUtil.format(DateUtil.offset(new Date(), DateField.MONTH, 1), DatePattern.NORM_DATE_PATTERN), price.getType());
    }
}
